/**
 * 
 */
package com.wubo.sec.filter;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wubo.sec.SecurityManager;
import com.wubo.sec.model.Group;
import com.wubo.sec.service.IGroupService;
import com.wubo.sec.util.ArrayUtils;

/**
 * @author WuBo
 * @CreateDate 2010-8-2
 * @version 1.0.01
 */
@Component("userBeforeFilter")
public class UserBeforeFilter implements IDataBeforeFilter {
	
	private IGroupService groupService;
	@Autowired
	public UserBeforeFilter(IGroupService groupService){
		this.groupService = groupService;
	}
	
	/* (non-Javadoc)
	 * @see com.asc.sf.filter.IDataBeforeFilter#getFilter()
	 */
	public String sift() {
		Group group = SecurityManager.getCurrentUser().getGroup();
		
		int priority = group.getPriority();
		String mark = group.getMark();
		
		//codes.add(group.getCode());
		
		List<Group> groups = groupService.findAccessibleGroups(priority, mark, group);
		
		if(groups.size() > 0){
			Set<String> codes = new HashSet<String>();
			for(int i=0; i<groups.size(); i++){
				codes.add(groups.get(i).getCode());
			}
			return " and ( u.group.code in ("+ArrayUtils.split(codes.toArray(), ",", "'")+") or u.owner = '"+SecurityManager.getCurrentUser().getUsername()+"')";
		} else {
			return " and u.owner = '"+SecurityManager.getCurrentUser().getUsername()+"'";
		}
	}
	
}
